import { MessageHandler, RequestProcessor, WsClient } from './WsClient';

const { regClass, property } = Laya;

@regClass()
export class LayaWsClient extends Laya.EventDispatcher {
    private static _instance: LayaWsClient;

    public static get instance() {
        if (!LayaWsClient._instance) {
            LayaWsClient._instance = new LayaWsClient();
        }
        return LayaWsClient._instance;
    }

    public onConnect: Laya.Handler;
    public onDisconnect: Laya.Handler;

    private wsClinet: WsClient;

    constructor() {
        super();
        this.wsClinet = new WsClient();
    }

    //todo  配置心跳和重连等
    public UseHeartBeatAndReconnect(): void {
        this.wsClinet.setHeartbeat(10000, true);
    }

    public UseReconnect(maxAttempts: number, delayMs: number): void {
        this.wsClinet.setReconnect(maxAttempts, delayMs);
    }

    //todo  二进制消息处理 比如上传 下载等
    //todo  处理图片消息

    public ConnectToServiceByUrl(url: string): void {
        this.wsClinet.connectByUrl(url);
    }

    public ConnectToService(host: string, port: number, isSecure: boolean = false): void {
        this.wsClinet.connect(host, port, isSecure);
    }

    //真正关闭连接,手动关闭
    public CloseToService(): void {
        this.wsClinet.close();
    }

    //注册无需回复消息的处理器
    public RegistryNomalMessageHandler(type: string, handler: MessageHandler): void {
        this.wsClinet.onMessageType(type, handler);
    }

    public UnRegistryNomalMessageHandler(type: string): void {
        this.wsClinet.offMessageType(type);
    }

    //注册，服务端主动请求消息的处理器  带requestId
    public RegistryServiceRequestMessageHandler(type: string, processor: RequestProcessor): void {
        this.wsClinet.registerRequestProcessor(type, processor);
    }

    public UnRegistryServiceRequestMessageHandler(type: string): void {
        this.wsClinet.unregisterRequestProcessor(type);
    }

    //发送请求消息，带requestId 自带超时处理
    public SendRequestMessage(type: string, data: any, timeout: number = 10000): Promise<any> {
        return this.wsClinet.sendRequest(type, data, timeout);
    }

    //发送通知消息
    public SendNotifyMessage(type: string, data: any): void {
        this.wsClinet.sendNotify(type, data);
    }
}
